package com.jzoffer2;
import ds.ListNode;

/**
 * TODO
 *
 * @author lefly
 * @version 1.0
 * @classname No22
 * @description 剑指 Offer 22. 链表中倒数第k个节点
 * @date 2021/1/29 下午12:57
 */
public class No22 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        ListNode l5 = new ListNode(5);
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;

        ListNode res = getKthFromEnd(l1,2);
        printListNode(res);

    }

    public static ListNode getKthFromEnd(ListNode head, int k) {
        if(head == null){
            return head;
        }
        ListNode fast = head,slow = head;
        for (int i = k; i > 0 && fast != null ; i--) {
            fast = fast.next;
        }
        while (fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

    public static void printListNode(ds.ListNode l){
        if(l == null){
            System.out.println("empty listnode");
        }else{
            while (l != null){
                System.out.print(l.val);
                System.out.print( " ");
                l = l .next;
            }
        }
    }

}
